package algorithm.string;

/**
 * 朴素算法 Brute-Force
 */
public class BruteForceMath {
    public static void main(String[] args) {
        char[] t = {'a','b','b','a','b','c','d'};
        char[] p = {'b','a'};
        //indexOf(t,p);
        indexOfExcellently(t,p);
    }
    //找位置
    static void indexOf(char[] t, char[] p) {
        int k = 0;
        int index = -1;
        String tmp = "";
        int excNum = 0;
        //todo 有bug,可优化
        for (int i = 0; i < t.length; i++) {
            for (int j=k;j<p.length;j++) {
                excNum++;
                if (t[i] == p[j]) {
                    tmp += t[i];
                    k++;
                    break;
                } else {
                    k=0;
                    tmp = "";
                }
            }
            if (k ==p.length) {
                index = i-p.length+1;
                break;
            }
        }
        if (k ==p.length) {
            System.out.println("finish:"+excNum+" index:"+index);
        } else {
            System.out.println("filed:"+excNum+" index:"+index);
        }
    }

    /**
     * 基于上面方法的优化（暴力破解）
     * @param t 主串
     * @param p 匹配串
     */
    static void indexOfExcellently(char[] t, char[] p) {
        int i = 0;
        int j = 0;
        int pass = 0;
        while(i < t.length-1 && j < p.length){
            System.out.println(i+"|"+j);
            if (t[i] == p[j]) {
                i++;
                j++;
            }
            else{
                pass++;
                i = pass;
                //i = i-j+1;// 一旦不匹配，i后退,pass可以不使用
                j = 0;
            }
            if ( pass >= t.length) {
                System.out.println("filed");
                break;
            }
        }
        if ( j == p.length  ) {
            System.out.println("success");
        } else {
            System.out.println("filed");
        }
        System.out.println("i:"+i+" pass:"+pass+" j:"+j);
    }


}








